package com.zhihaoliang.coroutine.buss.channel.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/27 16:54
 * @des 通道
 */
object ChannelPipeline {
    private fun CoroutineScope.produceNumbers() = produce<Int> {
        var x = 1
        while (true) send(x++) // 在流中开始从 1 生产无穷多个整数
    }

    private fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce {
        for (x in numbers) send(x * x * x)
    }

    fun onPipeline(mainScope: CoroutineScope) = mainScope.launch {
        val numbers = produceNumbers() // 从 1 开始生成整数
        val squares = square(numbers) // 整数求平方
        repeat(5) {
            log(squares.receive()) // 输出前五个
        }
        log("Done!") // 至此已完成
        coroutineContext.cancelChildren() // 取消子协程
    }
}